<?php
namespace app\send\logic\msg;
use app\send\logic\VerificationCodeLogic as Code;
use think\Hook;
use \think\Config;
/**
 * 手机发送短信
 */
class MsgLogic
{
	/**
	 * [index 发送验证码]
	 * @param  [type] $param.phone [手机号]
     * @param  [type] $param.captcha [图像验证码] 
     * @param  [type] $param.type [类型 1 阿里短信 2云片 3聚合短信 4短信宝 5创蓝253] 
	 * @return [type]     [description]
	 */
	public function index($param){
        $phone = $param['phone'];
        $captcha = empty($param['captcha']) ? 0 :$param['captcha'];

        $type = empty($param['type']) ? 0 :$param['type'];
        //正则验证手机格式
        if(!preg_match("/^1[34578]{1}\d{9}$/",$phone)){
            return [
                'code' => 0,
                'msg' => '手机格式不正确',
            ];
        }
        //图像验证码
        $res = Hook::listen('captcha',$captcha,'',true);
        if(!$res){
            return [
                'code' => 0,
                'msg' => '图形验证码不正确',
            ];
        }
        //检查手机或邮箱是否还可以发送验证码,并返回生成的验证码
        $mverificationCodeModel = new Code();
        $code = $mverificationCodeModel->cmf_get_verification_code($phone);
        if(!$code){
        	return [
        		'code' => 0,
        		'msg' => '达到短信发送上线',
        	];

        }   
        $data = [
                'phone'=>$phone,
                'code'=>$code,
            ];
        //发送短信
        $rs = Hook::listen('message',$data,$type,true);
        //发送成功后
        if($rs['code'] == 1){
        	//更新为最新验证码
            $time = Config::get('code_time');
        	$rs = $mverificationCodeModel->saveCode($phone,$code,time()+(int)$time);
        	if($rs){
                return [
	        		'code' => 1,
	        		'msg' => $code,
	        	];
        	}
        }
        return [
        		'code' => 0,
        		'msg' => $rs['msg'],
        	];

	}
}

